package org.csu.petstore.ssm.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.csu.petstore.ssm.entity.Account;
import org.csu.petstore.ssm.entity.Product;
import org.csu.petstore.ssm.service.AccountService;

import org.csu.petstore.ssm.service.CatalogService;
import org.csu.petstore.ssm.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import jakarta.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    CatalogService catalogService;
    String msg;
    @GetMapping("myaccount")
    public String myaccount(Model model,HttpSession session) {
        Account account = (Account) session.getAttribute("loginAccount");
        if (account == null) {
            return "account/accountnull";
        } else {
            model.addAttribute("loginAccount",account);
            return "account/IncludeAccountFields";
        }
    }

    @GetMapping("registerform")
    public String registerform(Account account) {

        return "account/AddAccountForm";

    }

    @PostMapping ("register")
    public String register(Account account,@RequestParam("repeatPassword")String repeatedPassword, String code, Model model,HttpSession session) {
        account.setStatus("OK");
        String correct_code=(String) session.getAttribute("code");
        boolean flag=false;
        if(!repeatedPassword.equals(account.getPassword())){
            this.msg="different password";
            flag=true;
        }
        if (code == null || !code.equalsIgnoreCase(correct_code)) {
            this.msg = "Invalid captcha.";
            flag = true;
        }
        if(!validate(account)||flag){
            model.addAttribute("RegisterMsg", this.msg);
            return "account/AddAccountForm";
        }else{

            accountService.insertAccount(account);
            return "catalog/main";
        }


    }
    public boolean validate(Account account){
        String username=account.getUserid();


        if(accountService.selectAccountByUsername(username)){
            this.msg="Account name already exist";
            return false;
        }
        if(account.getUserid()==null||account.getUserid().equals("") ){
            this.msg="Username is required";
            return false;
        }
        if(account.getPassword()==null||account.getPassword().equals("") ){
            this.msg="Password is required";
            return false;
        }
        if(account.getFirstName()==null||account.getFirstName().equals("") ){
            this.msg="First name is required";
            return false;
        }
        if(account.getLastName()==null||account.getLastName().equals("") ){
            this.msg="Last name is required";
            return false;
        }
        if(account.getEmail()==null||account.getEmail().equals("") ){
            this.msg="Email is required";
            return false;
        }
        if(account.getPhone()==null||account.getPhone().equals("") ){
            this.msg="Phone is required";
            return false;
        }
        if(account.getAddress1()==null||account.getAddress1().equals("") ){
            this.msg="Address1 is required";
            return false;
        }
        if(account.getAddress2()==null||account.getAddress2().equals("") ){
            this.msg="Address2 is required";
            return false;
        }
        if(account.getCity()==null||account.getCity().equals("") ){
            this.msg="City is required";
            return false;
        }
        if(account.getState()==null||account.getState().equals("")){
            this.msg="State is required";
            return false;
        }
        if(account.getCountry()==null||account.getCountry().equals("")){
            this.msg="Country is required";
            return false;
        }
        if(account.getZip()==null||account.getZip().equals("")){
            this.msg="Zip is required";
            return false;
        }
        return true;
    }

    @GetMapping("signonform")
    public String signonform() {
        return "account/signon";
    }


    @PostMapping("signon")
    public String signon(String username, String password, HttpSession session, String code, Model model) {
        String correct_code = (String) session.getAttribute("code");

        if (!validate(username, password, msg)) {
            model.addAttribute("signOnMsg", this.msg);
            return "account/signon";
        }

        if (code != null && code.equals(correct_code)) {
            Account loginAccount = accountService.getAccount(username, password);
            boolean test = accountService.selectAccountByUsername(username);
            boolean test1 = accountService.selectAccountByPassword(password);

            System.out.println(loginAccount);
            if (loginAccount != null) {
                session.setAttribute("loginAccount", loginAccount);

                if (loginAccount.isListOption()) {
                    List<Product> myList = catalogService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                    session.setAttribute("myList", myList);
                }
                return "catalog/main";
            } else {
                msg = "用户名或密码错误";
                model.addAttribute("signOnMsg", this.msg);
                return "account/signon";
            }
        } else {
            msg = "验证码错误";
            model.addAttribute("signOnMsg", msg);
            return "account/signon";
        }
    }



    public boolean validate(String username,String password,String msg){
        if(username.equals("") || username==null){
            msg = "用户名为空";
            return false;
        }
        if(password.equals("") || password==null){
            msg = "密码为空";
            return false;
        }
        if(username.length()>8){
           msg = "用户名过长";
            return false;
        }
        if(password.length()>8){
          msg = "密码过长";
            return false;
        }
        return true;
    }

    @GetMapping("signout")
    public String signout(Model model,HttpSession session) {
        session.removeAttribute("loginAccount");
        session.removeAttribute("cartMsg");
        return "catalog/main";
    }

    @PostMapping("updateaccount")
    public String updateaccount(Account account, Model model,HttpSession session) {
        account.setStatus("OK");
        session.setAttribute("loginAccount", account);
        accountService.updateAccount(account);
        return "catalog/main";
    }


    @ResponseBody
    @GetMapping("usernameexist")
    public String usernameexist(String username) {
        Account account = accountService.getAccountByUsername(username);
        if (account != null)
            return "Exist";
        else return "Not Exist";
    }

    @GetMapping("captcha")
    public ResponseEntity<byte[]> getCaptcha(HttpSession session) throws IOException {
        String captchaText = defaultKaptcha.createText();
        session.setAttribute("code", captchaText);

        BufferedImage captchaImage = defaultKaptcha.createImage(captchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "png", outputStream);
        byte[] imageBytes = outputStream.toByteArray();

        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_PNG)
                .body(imageBytes);


    }

}